package com.shun.auth.action;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.shun.auth.service.SliderService;
import com.shun.common.R;
import com.shun.common.constants.ShunConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 平台验证码服务
 *
 * @author clever
 * @since 2021-09-24
 */
@Slf4j
@RequestMapping("/auth")
@RestController
public class ShunValidateCodeAction extends ShunAuthBaseAction{

    /**
     * 生成滑块拼图验证码
     * @return
     */
    @GetMapping("/validateCode/{accountStr}")
    public R getImageVerifyCode(@PathVariable("accountStr") String accountStr) {
        //账号密码登录,AES解密密码
        String account = decryptStr(accountStr);
        stringRedisTemplate.opsForValue().set(ShunConstant.SHUN_REDIS_ATUH+account,"0",1,TimeUnit.MINUTES);
        long accountCount = stringRedisTemplate.opsForValue().increment(ShunConstant.SHUN_REDIS_ATUH+account);
        log.debug("accountCount:{}",accountCount);
        if( accountCount > 3) {
            return R.error("当前登录过于频繁，请稍后再试！");
        }
        Map<String, Object> resultMap = new HashMap<>();
        File file = new File(authProperty.getImagePath());
        File[] files = file.listFiles();
        File imageFile = files[new Random().nextInt(files.length)];
        SliderService.createImage(imageFile, resultMap);
        String dKey = DateUtil.current()+ RandomUtil.randomNumbers(6);
        String imgCode = Base64Encoder.encode(dKey);
        stringRedisTemplate.opsForValue().set(ShunConstant.SHUN_REDIS_ATUH+dKey, StrUtil.toString(resultMap.get("xWidth")),1, TimeUnit.MINUTES);
        log.debug("x:{},imgCode:{}",resultMap.get("xWidth"),imgCode);
        resultMap.remove("xWidth");
        resultMap.put("imgCode", imgCode);
        return R.suc(resultMap);
    }
}
